#include "Character.h"
#include "Map.h"

Character::Character(void)
{
}

Character::~Character(void)
{
}

void Character::Load()
{
	mSprite.Load("pikachu.png");
}

void Character::Unload()
{
	mSprite.Unload();
}

void Character::Update(float deltaTime,const Map& map)
{
	const float kSpeed = 1000.0f;
	float displacementX = 0.0f;

	//x values --------------
	if(Input_IsKeyDown(Keys::RIGHT))
	{
		displacementX = kSpeed * deltaTime;
	}
	else if(Input_IsKeyDown(Keys::LEFT))
	{
		displacementX = -kSpeed * deltaTime;
	}

	SRect boundingBox = GetBoundingBox() + SVector2(displacementX, 0.0f);
	if(displacementX > 0.0f)
	{
		//Check right
		SLineSegment segment = boundingBox.GetRightSegment();
		SRect collisionBox;
		if(map.TestCollision(segment , collisionBox))
		{
			displacementX -= (boundingBox.max.x - collisionBox.min.x + 1.0f);
			mPosition.x += (int)displacementX;
		}
		else
		{
			mPosition.x += (int)displacementX;
		}
	}
	else if (displacementX < 0.0f)
	{
		//TODO :Check left
		SLineSegment segment = boundingBox.GetLeftSegment();
		SRect collisionBox;
		if(map.TestCollision(segment , collisionBox))
		{
			displacementX += (collisionBox.max.x - boundingBox.min.x + 1.0f);
			mPosition.x += (int)displacementX;
		}
		else
		{
			mPosition.x += (int)displacementX;
		}
	}

	float displacementY = 0.0f;

	//y values --------------
	if(Input_IsKeyDown(Keys::UP))
	{
		displacementY = -kSpeed * deltaTime;
	}

	else if(Input_IsKeyDown(Keys::DOWN))
	{
		displacementY = kSpeed * deltaTime;
	}
	
	boundingBox = GetBoundingBox() + SVector2(0.0f, displacementY);

	if (displacementY > 0.0f)
	{
		//TODO :Check down
		SLineSegment segment = boundingBox.GetBottomSegment();
		SRect collisionBox;
		if(map.TestCollision(segment , collisionBox))
		{
			displacementY -= (boundingBox.max.y - collisionBox.min.y + 1.0f);
			mPosition.y += (int)displacementY;
		}
		else
		{
			mPosition.y += (int)displacementY;
		}
	}
	else if(displacementY < 0.0f)
	{
		//TODO :Check up
		SLineSegment segment = boundingBox.GetTopSegment();
		SRect collisionBox;
		if(map.TestCollision(segment , collisionBox))
		{
			displacementY +=  (collisionBox.max.y - boundingBox.min.y + 1.0f);
			mPosition.y += (int)displacementY;
		}
		else
		{
			mPosition.y += (int)displacementY;
		}
	}
}	
	
	
void Character::Render(const SVector2& viewOffset)
{
	const int width = mSprite.GetWidth();
	const int height = mSprite.GetHeight();
	SVector2 offset(width * 0.5f, height * 0.5f);
	SVector2 renderPosition = mPosition - offset - viewOffset;
	mSprite.SetPosition(renderPosition);
	mSprite.Render();
}

SRect Character::GetBoundingBox() const
{
	SRect boundingBox;
	boundingBox.min.x = mPosition.x - 32.0f;
	boundingBox.max.x = mPosition.x + 32.0f;
	boundingBox.min.y = mPosition.y - 50.0f;
	boundingBox.max.y = mPosition.y + 50.0f;
	return boundingBox;
}